﻿using Furion.DependencyInjection;
using IMES.Entity;
using SqlSugar;
using System.Data;

namespace IMES.BLL
{
    /// <summary>
    /// 报表-仓储处理
    /// </summary>
    public class ReportRep : BaseRepository<Report>, ITransient
    {
        /// <summary>
        /// 根据菜单/报表编号 加载报表详情
        /// </summary>
        /// <param name="menuNo"></param>
        /// <returns></returns>
        public Report LoadDtlByNo(string menuNo)
        {
            Report rep = Context.Queryable<Report>().Where(a => a.MenuNo.Equals(menuNo)).First();
            if (rep != null)
            {
                rep.Conditions = Context.Queryable<ReportCondition>().Where(a => rep.Id.Equals(a.ReportId)).ToList();
                rep.Columns = Context.Queryable<ReportColumn>().Where(a => rep.Id.Equals(a.ReportId)).ToList();
            }
            return rep;
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="report"></param>
        /// <returns></returns>
        public DataTable GetData(Report report)
        {
            List<SugarParameter> pars = new List<SugarParameter>();
            if (report.Conditions != null && report.Conditions.Count > 0)
            {
                foreach (var condition in report.Conditions)
                {
                    pars.Add(new SugarParameter(condition.ConName, (condition.DefaultValue!=null)? condition.DefaultValue:"",System.Data.DbType.String));
                }
            }
            DataTable dt = Context.Ado.GetDataTable(report.SQL, pars);
            return dt;
        }

        public void Save(Report report)
        { 
            //更新报表
            var oldReport=Context.Queryable<Report>().Where(a => a.Id.Equals(report.Id)).First();
            if (oldReport == null)
                Context.Insertable<Report>(report).ExecuteCommand();
            else
                Context.Updateable<Report>(report).ExecuteCommand();
            //重新添加报表条件
            if(report.Conditions?.Count>0)
            {
                Context.Deleteable<ReportCondition>(rc => rc.ReportId.Equals(report.Id)).ExecuteCommand();
                Context.Insertable<ReportCondition>(report.Conditions).ExecuteCommand();
            }
            //重新添加报表展示字段
            if(report.Columns?.Count > 0)
            {
                Context.Deleteable<ReportColumn>(rcl=>rcl.ReportId.Equals(report.Id)).ExecuteCommand();
                Context.Insertable<ReportColumn>(report.Columns).ExecuteCommand();
            }
        }
    }
}
